package com.x52im.rainbowchat.http.logic.pay.redenvelope;

import com.alibaba.fastjson.JSON;
import com.x52im.rainbowchat.http.logic.dto.RedEnvelopeDTO;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 查询红包列表
 */
public class MRedEnvelopeQuery extends ARedEnvelope {
    @Override
    public String deal(RedEnvelopeDTO dto) throws Exception {
        // 查询当前红包中已领取的红包列表
        List<RedEnvelopeDTO> redEnvelopeDTOS = moneyDAO.queryRedEnvelopsRoot(dto, true);
        RedEnvelopeDTO root = redEnvelopeDTOS.get(0);
        List<RedEnvelopeDTO> subs = root.getSubRedEnvelopeDTOS();
        long getNum = subs.stream().filter(redEnvelope -> redEnvelope.getState().equals(RedEnvelopeDTO.STATE.STATE_FINISH.getState())).count();
        long getMoney = subs.stream()
                .filter(redEnvelope -> redEnvelope.getState().equals(RedEnvelopeDTO.STATE.STATE_FINISH.getState()))
                .mapToInt(value -> Integer.parseInt(value.getTotalAmount())).sum();
        root.setGetNum(String.valueOf(getNum));
        root.setGetMoney(String.valueOf(getMoney));

        // 如果红包已经领完了才展示手气王
        if (root.getState().equals(RedEnvelopeDTO.STATE.STATE_FINISH_ALL.getState())) {
            List<RedEnvelopeDTO> maxss = new ArrayList<>();
            int maxAmout = subs.stream().mapToInt(value -> Integer.parseInt(value.getTotalAmount())).max().getAsInt();
            for (int i = 0; i < subs.size(); i++) {
                RedEnvelopeDTO sub = subs.get(i);
                if (sub.getTotalAmountInt() == maxAmout) {
                    sub.setIsMax("1");
                    maxss.add(sub);
                }
            }
            if (maxss.size() > 1) {
                // 多个金额最大的红包时再增加时间判断,先领到的是运气王
                List<RedEnvelopeDTO> sortedMaxss = maxss.stream()
                        .sorted((o1, o2) -> Long.compare(convertTimeToLong(o1.getStateDate()), convertTimeToLong(o2.getStateDate())))
                        .collect(Collectors.toList());
                String maxId = sortedMaxss.get(0).getId();
                subs.stream().forEach(redEnvelopeDTO -> {
                    if (redEnvelopeDTO.getId().equals(maxId)) {
                        redEnvelopeDTO.setIsMax("1");
                    } else {
                        redEnvelopeDTO.setIsMax("0");
                    }
                });
            }
        }

        return JSON.toJSONString(root);
    }

    private Long convertTimeToLong(String time) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime parse = LocalDateTime.parse(time, formatter);
        return LocalDateTime.from(parse).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }
}
